package com.ruoyi.system.service.impl;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.mybatisPlus.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysDictType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.mapper.SysDictTypeMapper;
import com.ruoyi.system.service.ISysDictTypeService;

import javax.annotation.PostConstruct;

/**
 * 字典 业务层处理
 * 
 * @author ruoyi
 */
@Service
public class SysDictTypeServiceImpl extends BaseServiceImpl<SysDictTypeMapper, SysDictType> implements ISysDictTypeService
{
    @Autowired
    private SysDictTypeMapper dictTypeMapper;

    @Autowired
    private SysDictDataMapper dictDataMapper;

    /**
     * 项目启动时，初始化字典到缓存
     */
    @PostConstruct
    public void init()
    {
        loadingDictCache();
    }

    /**
     * 根据条件分页查询字典类型
     * 
     * @param dictType 字典类型信息
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictType> selectDictTypeList(SysDictType dictType)
    {
//        return dictTypeMapper.selectDictTypeList(dictType);
        LambdaQueryWrapper<SysDictType> wrapper = new LambdaQueryWrapper<>();

        // 构建查询条件
        wrapper.like(StringUtils.isNotBlank(dictType.getDictName()), SysDictType::getDictName, dictType.getDictName())
                .eq(StringUtils.isNotBlank(dictType.getStatus()), SysDictType::getStatus, dictType.getStatus())
                .like(StringUtils.isNotBlank(dictType.getDictType()), SysDictType::getDictType, dictType.getDictType());

        // 处理时间范围查询
        if (dictType.getParams() != null) {
            if (ObjectUtil.isNotEmpty(dictType.getParams().get("beginTime"))) {
                wrapper.ge(SysDictType::getCreateTime, DateUtils.parseDate(dictType.getParams().get("beginTime")));
            }
            if (ObjectUtil.isNotEmpty(dictType.getParams().get("endTime"))) {
                wrapper.le(SysDictType::getCreateTime, DateUtils.parseDate(dictType.getParams().get("endTime")));
            }
        }

        // 执行分页查询
        return dictTypeMapper.selectList(wrapper);
    }

    /**
     * 根据所有字典类型
     * 
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictType> selectDictTypeAll()
    {
//        return dictTypeMapper.selectDictTypeAll();
        LambdaQueryWrapper<SysDictType> wrapper = new LambdaQueryWrapper<>();
        return dictTypeMapper.selectList(wrapper);
    }

    /**
     * 根据字典类型查询字典数据
     * 
     * @param dictType 字典类型
     * @return 字典数据集合信息
     */
    @Override
    public List<SysDictData> selectDictDataByType(String dictType)
    {
        List<SysDictData> dictDatas = DictUtils.getDictCache(dictType);
        if (StringUtils.isNotEmpty(dictDatas))
        {
            return dictDatas;
        }
//        dictDatas = dictDataMapper.selectDictDataByType(dictType);
        LambdaQueryWrapper<SysDictData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictData::getDictType, dictType);
        queryWrapper.eq(SysDictData::getStatus, "0");
        queryWrapper.orderByAsc(SysDictData::getDictSort);
        dictDatas =  dictDataMapper.selectList(queryWrapper);
        if (StringUtils.isNotEmpty(dictDatas))
        {
            DictUtils.setDictCache(dictType, dictDatas);
            return dictDatas;
        }
        return null;
    }

    /**
     * 根据字典类型ID查询信息
     * 
     * @param dictId 字典类型ID
     * @return 字典类型
     */
    @Override
    public SysDictType selectDictTypeById(Long dictId)
    {
//        return dictTypeMapper.selectDictTypeById(dictId);
        LambdaQueryWrapper<SysDictType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictType::getDictId, dictId);
        return dictTypeMapper.selectOne(queryWrapper);
    }

    /**
     * 根据字典类型查询信息
     * 
     * @param dictType 字典类型
     * @return 字典类型
     */
    @Override
    public SysDictType selectDictTypeByType(String dictType)
    {
//        return dictTypeMapper.selectDictTypeByType(dictType);
        LambdaQueryWrapper<SysDictType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictType::getDictType, dictType);
        return dictTypeMapper.selectOne(queryWrapper);
    }

    /**
     * 批量删除字典类型信息
     * 
     * @param dictIds 需要删除的字典ID
     */
    @Override
    public void deleteDictTypeByIds(Long[] dictIds)
    {
        for (Long dictId : dictIds)
        {
            SysDictType dictType = selectDictTypeById(dictId);
            LambdaQueryWrapper<SysDictData> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysDictData::getDictType, dictType.getDictType());
            Integer i = dictDataMapper.selectCount(queryWrapper);
//            if (dictDataMapper.countDictDataByType(dictType.getDictType()) > 0)
            if (i > 0)
            {
                throw new ServiceException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
            }
//            dictTypeMapper.deleteDictTypeById(dictId);
            dictTypeMapper.deleteById(dictId);
            DictUtils.removeDictCache(dictType.getDictType());
        }
    }

    /**
     * 加载字典缓存数据
     */
    @Override
    public void loadingDictCache()
    {
        SysDictData dictData = new SysDictData();
        dictData.setStatus("0");
        LambdaQueryWrapper<SysDictData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ObjectUtil.isNotEmpty(dictData.getDictType()),SysDictData::getDictType, dictData.getDictType());
        queryWrapper.eq(ObjectUtil.isNotEmpty(dictData.getStatus()),SysDictData::getStatus, dictData.getStatus());
        queryWrapper.eq(ObjectUtil.isNotEmpty(dictData.getDictLabel()),SysDictData::getDictLabel, dictData.getDictLabel());
        queryWrapper.orderByAsc(SysDictData::getDictSort);
        List<SysDictData> sysDictData = dictDataMapper.selectList(queryWrapper);
//        Map<String, List<SysDictData>> dictDataMap = dictDataMapper.selectDictDataList(dictData).stream().collect(Collectors.groupingBy(SysDictData::getDictType));
        Map<String, List<SysDictData>> dictDataMap = sysDictData.stream().collect(Collectors.groupingBy(SysDictData::getDictType));
        for (Map.Entry<String, List<SysDictData>> entry : dictDataMap.entrySet())
        {
            DictUtils.setDictCache(entry.getKey(), entry.getValue().stream().sorted(Comparator.comparing(SysDictData::getDictSort)).collect(Collectors.toList()));
        }
    }

    /**
     * 清空字典缓存数据
     */
    @Override
    public void clearDictCache()
    {
        DictUtils.clearDictCache();
    }

    /**
     * 重置字典缓存数据
     */
    @Override
    public void resetDictCache()
    {
        clearDictCache();
        loadingDictCache();
    }

    /**
     * 新增保存字典类型信息
     * 
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    public int insertDictType(SysDictType dict)
    {
//        int row = dictTypeMapper.insertDictType(dict);
        int row = dictTypeMapper.insert(dict);
        if (row > 0)
        {
            DictUtils.setDictCache(dict.getDictType(), null);
        }
        return row;
    }

    /**
     * 修改保存字典类型信息
     * 
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateDictType(SysDictType dict)
    {
//        SysDictType oldDict = dictTypeMapper.selectDictTypeById(dict.getDictId());
//        dictDataMapper.updateDictDataType(oldDict.getDictType(), dict.getDictType());
        LambdaQueryWrapper<SysDictType> queryWra = new LambdaQueryWrapper<>();
        queryWra.eq(SysDictType::getDictId, dict.getDictId());
        SysDictType oldDict =  dictTypeMapper.selectOne(queryWra);

        LambdaUpdateWrapper<SysDictData> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(SysDictData::getDictType, dict.getDictType());
        updateWrapper.eq(SysDictData::getDictType, oldDict.getDictType());
        dictDataMapper.update(null, updateWrapper);

//        int row = dictTypeMapper.updateDictType(dict);
        int row = dictTypeMapper.updateById(dict);
        if (row > 0)
        {
//            List<SysDictData> dictDatas = dictDataMapper.selectDictDataByType(dict.getDictType());
            LambdaQueryWrapper<SysDictData> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysDictData::getDictType, dict.getDictType());
            queryWrapper.eq(SysDictData::getStatus, "0");
            queryWrapper.orderByAsc(SysDictData::getDictSort);
            List<SysDictData> dictDatas =  dictDataMapper.selectList(queryWrapper);
            DictUtils.setDictCache(dict.getDictType(), dictDatas);
        }
        return row;
    }

    /**
     * 校验字典类型称是否唯一
     * 
     * @param dict 字典类型
     * @return 结果
     */
    @Override
    public boolean checkDictTypeUnique(SysDictType dict)
    {
        Long dictId = StringUtils.isNull(dict.getDictId()) ? -1L : dict.getDictId();
//        SysDictType dictType = dictTypeMapper.checkDictTypeUnique(dict.getDictType());
        LambdaQueryWrapper<SysDictType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictType::getDictType, dict.getDictType());
        SysDictType dictType =  dictTypeMapper.selectOne(queryWrapper);
        if (StringUtils.isNotNull(dictType) && dictType.getDictId().longValue() != dictId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
}
